package com.zcf.airobot.config;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author zcf
 * 切面类
 */
@Aspect
@Component
public class LogToFileAspect {


    //1.定义切点；2.定义通知
    @Around("@annotation(com.zcf.airobot.config.Log)")
    public Object logToFile(ProceedingJoinPoint joinPoint) throws Throwable {
        //通过反射去实现
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();//获取方法签名
        //获取方法上的注解
        Log annotation = methodSignature.getMethod().getAnnotation(Log.class);

        // 获取方法信息
        String className = joinPoint.getTarget().getClass().getName();
        String methodName =methodSignature.getMethod().getName();
        Object[] args = joinPoint.getArgs();

        // 记录方法开始时间
        long startTime = System.currentTimeMillis();

        // 执行目标方法
        Object result = joinPoint.proceed();

        // 计算执行耗时
        long executionTime = System.currentTimeMillis() - startTime;

        // 构建日志内容
        String logContent = String.format("[%s] %s.%s() - 参数: %s, 返回值: %s, 耗时: %dms",
                LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME),
                className,
                methodName,
                arrayToString(args),
                result,
                executionTime);

        //写入文件
        writeToFile(annotation.logFilePath(), logContent);

       return result;
    }


    private String arrayToString(Object[] array) {
        if (array == null || array.length == 0) {
            return "[]";
        }
        StringBuilder sb = new StringBuilder("[");
        for (Object obj : array) {
            sb.append(obj).append(", ");
        }
        sb.delete(sb.length() - 2, sb.length());
        sb.append("]");
        return sb.toString();
    }


    private synchronized void writeToFile(String fileName, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true))) {
            writer.write(content);
            writer.newLine();
        } catch (IOException e) {
            System.err.println("写入日志文件失败: " + e.getMessage());
        }
    }
}
